package com.example.service.Impl;

import com.example.Mapper.UserMapper;
import com.example.Utils.UserHolder;
import com.example.pojo.PageInfo;
import com.example.pojo.Result;
import com.example.pojo.User;
import com.example.pojo.Constants.UserRedisConstants;
import com.example.service.UserService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.logging.Logger;
import org.mybatis.logging.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    private static final ObjectMapper mapper = new ObjectMapper();


    /**
     * 登录判断
     * @param user
     */
    @Override
    public boolean login(User user) {

        Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

        String password = user.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        User checkUser = userMapper.getByUsername(user.getUsername());

        if(checkUser == null){
            return false;
        }else{
            UserHolder.saveUser(checkUser);
            int id = UserHolder.getUser().getId();
            redisTemplate.opsForValue().set(UserRedisConstants.USER_LOGIN+id,1);
            return checkUser.getPassword().equals(password);
        }
    }

    @Override
    public void insert(User user) {
        // 密文存储
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        userMapper.insert(user);

    }

    @Override
    public Result<PageInfo> pageQuery(int page, int pageSize) {

        PageHelper.startPage(page,pageSize);
        List<User> list =  userMapper.selectAll();

        int total = list.size();

        return Result.success(new PageInfo(total,list));
    }

    /**
     * 查询用户信息
     * @param id
     * @return
     */
    @Override
    public User getById(int id) {
        ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();
        String jsonStr = valueOperations.get(UserRedisConstants.USER + id);
        User user = null;
        if(jsonStr == null){
            log.info("查询数据库----------");
            user = userMapper.getById(id);
            try {
                jsonStr = mapper.writeValueAsString(user);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
            valueOperations.set(UserRedisConstants.USER + id, jsonStr);
        }else{
            try {
                log.info("查询缓冲区-------------");
                user = mapper.readValue(jsonStr,User.class);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }
        return user;
    }
}

//        ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();
//        String jsonStr = valueOperations.get(UserRedisConstants.USER + id);
//
//        if (jsonStr == null) {
//            // 缓存中不存在，从数据库中查询
//            log.info("数据载入缓冲区------------");
//            User user = userMapper.getById(id);
//            if (user != null) {
//                ObjectMapper objectMapper = new ObjectMapper();
//                try {
//                    jsonStr = objectMapper.writeValueAsString(user);
//                    valueOperations.set(UserRedisConstants.USER + id, jsonStr);
//                } catch (JsonProcessingException e) {
//                    e.printStackTrace();
//                }
//            }
//            return user;
//        } else{
//            // 存在缓存，进行反序列化操作
//            log.info("查询缓冲区-------------------");
//            ObjectMapper objectMapper = new ObjectMapper();
//            try {
//                User user = objectMapper.readValue(jsonStr, User.class);
//                return user;
//            } catch (JsonProcessingException e) {
//                e.printStackTrace();
//            }
//        }
//        return null;
